package com.guoxue.action.front;

import java.text.NumberFormat;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoxue.domain.BookConfigVo;
import com.guoxue.domain.PlanConfigVo;
import com.guoxue.domain.PlanProgressVo;
import com.guoxue.domain.PlayerProgressVo;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.UserVo;
import com.guoxue.service.IBookConfigService;
import com.guoxue.service.IPlanConfigService;
import com.guoxue.service.IPlanProgressService;
import com.guoxue.service.IPlayerProgressService;
import com.guoxue.service.ITapesRecordsService;
import com.guoxue.service.IUserService;
import com.guoxue.util.JsonUtil;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.OtherUtils;
/**
 * 诵读功能模块接口
 * @author young
 *
 */
@Controller
@RequestMapping("Read")
public class ReadAction extends BaseAction{
	
	@Resource
	private IPlayerProgressService playerService;
	@Resource
	private IPlanProgressService planService;
	@Resource
	private IPlanConfigService planConfigService;
	@Resource
	private IBookConfigService bookService;
	@Resource
	private IUserService userService;
	@Resource
	private ITapesRecordsService tapesService;
	/**
	 *  进度上传接口
	 * @param req
	 * @param resp
	 * @param exp
	 * @param medal
	 * @param planId
	 * @param sentence
	 * @param readRound
	 * @param readCount
	 * @return
	 */
	@RequestMapping("/planCommit")
	@ResponseBody
	public JSON playerProgressCommit(HttpServletRequest req, HttpServletResponse resp, 
			 Integer planId,Integer sentence){
		try {
			if (planId==null||sentence==null){
				return Message(ERROR, "参数不全请检查参数", null);
			} 
			UserVo user = (UserVo)req.getSession().getAttribute("user");
			if (user==null){
				return Message(ERROR, "获取用户信息失败", null);
			} else {
				PlayerProgressVo pp = playerService.getPlayerProgressByUid(user.getId());
				PlanConfigVo pc = planConfigService.getPlanConfig(planId);
				PlanProgressVo ppr = planService.getPlanByUserAndPlanId(user.getId(), planId);
				if (pc==null){
					return Message(ERROR, "未查询到当前计划", null);
				}
				int count=0;
				int medal =0;
				int round = 0;
				int exp = 0;
				boolean flag = pc.getEndWordId()==sentence;    //判断单次是否读完
				PlanProgressVo progress = new PlanProgressVo();
				if (ppr==null){ //判断是否为首次诵读该计划
					progress.setCurrentPlanId(planId);
					progress.setUid(user.getId());
					if (flag){ // 是否完成单次诵读
						if (pc.getCount()==1){ //若该计划为 读一次为一轮，则给分以及奖牌.
							round=1;
							medal=pc.getFirstMedal();
							exp=pc.getFirstExp();
							sentence = 0;
						} else {  //否则只对当前计划读次数加1
							count=1;
						}
					} 
					progress.setCurrentReadCount(count);
					progress.setCurrentReadRound(round);
					progress.setMedal(medal);
					progress.setCurrentSentence(sentence);
					planService.savePlan(progress);
				} else { //非首次读该计划 
					if (flag) {
						if (pc.getCount()==(ppr.getCurrentReadCount()+1)){
							round = ppr.getCurrentReadRound()+1;
							if (round==1){ //首次奖励
								ppr.setMedal(ppr.getMedal()+pc.getFirstMedal());
								ppr.setCurrentReadRound(round);
								ppr.setCurrentReadCount(0);
								ppr.setCurrentSentence(0);
								exp = pc.getFirstExp();
								medal = pc.getFirstMedal();
							} else { //非首次奖励
								ppr.setMedal(ppr.getMedal()+pc.getMedal());
								ppr.setCurrentReadRound(round);
								ppr.setCurrentReadCount(0);
								ppr.setCurrentSentence(0);
								exp=pc.getExp();
								medal = pc.getMedal();
							}
						} else {
							ppr.setCurrentReadCount(ppr.getCurrentReadCount()+1);
						}
					} else {
						ppr.setCurrentSentence(sentence);
					}
					planService.savePlan(ppr);
				}
				if (pp==null){
					
//					pp = new PlayerProgressVo(medal, exp, 0, user.getId());
//					----kanghongbo重新构造------
					pp=new PlayerProgressVo();
					pp.setMedals(medal);
					pp.setExp(exp);
					pp.setUid(user.getId());
//	               ----------------------------				
				} else {
					pp.setExp(pp.getExp()+exp);
					pp.setMedals(pp.getMedals()+medal);
				}
				playerService.savePlayerProgress(pp);
				JSONObject obj = new JSONObject();
				obj.put("medal", medal);
				obj.put("exp", exp);
				return Message(SUCCESS, "数据提交成功", obj);//返回当前获取经验与奖牌数
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e,"用户数据提交异常");
		}
	}
	/**
	 * 或缺用户信息以及相关计划进度信息
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("/getProgress")
	@ResponseBody
	public JSON getProgress(HttpServletRequest req, HttpServletResponse resp){
		try {
			 UserVo user = (UserVo) req.getSession().getAttribute("user");
			 JSONObject data = new JSONObject();
			 JSONObject obj = new JSONObject();
			if (user!=null){			 //获取用户真实进度
				 PlayerProgressVo pp = playerService.getPlayerProgressByUid(user.getId()); 
				 List<BookConfigVo> books = bookService.getBookConfigList();
				 JSONObject plan = null;
				 JSONArray conf = new JSONArray();
				 for (BookConfigVo book:books){       //按单个计划获取所配置的总奖牌数、作者名，书名等相关信息
					 int total = 0;
					 int acquireMedal=0;
					 int begin = book.getBeginPlanId();
					 int end = book.getEndPlanId();
					 int readers = planService.getReadersCount(user.getId(),begin,end);
					 List<PlanConfigVo> lpc = planConfigService.getPlanConfigListByPlan(begin, end);
					 plan = new JSONObject();
					 plan.put("bookId", book.getBookId());
					 plan.put("bookName", book.getBookName());
					 plan.put("bookWriter", book.getWriter());
					 plan.put("bookReader",book.getReader());
					 for (PlanConfigVo pl : lpc){
							total = total+pl.getFirstMedal();
					 }
					 plan.put("total", total);
					 plan.put("currentReader", readers);   //获取当前该书在读人数
					 List<PlanProgressVo> lp = planService.getUserPlansByPlanId(user.getId(),book.getBeginPlanId(),book.getEndPlanId());
					 if (lp.size()==0){
						 plan.put("acquireMedal", 0);
					 } else {
						 for(PlanProgressVo pps:lp){
							 acquireMedal = acquireMedal+pps.getMedal();
						 }
						 plan.put("acquireMedal", acquireMedal);
					 }
					 conf.add(plan);
				 }
				 if (pp!=null){    //获取用户等级，总奖牌数，经验，头像等相关信息
					obj.put("nickName", user.getNickName());
					obj.put("exp", pp.getExp());
					obj.put("headImg", user.getImgUrl());
					data.put("userInfo", obj);
					data.put("progress", conf);
					return Message(SUCCESS, "获取用户信息成功", data);
				 } else {
					obj.put("nickName", user.getNickName());
					obj.put("level",1);
					obj.put("exp", 0);
					obj.put("headImg", user.getImgUrl());
				  }
					data.put("userInfo", obj);
					data.put("progress", conf);
					return Message(SUCCESS, "获取用户信息成功", data);
			}else{
				return Message(ERROR, "获取用户失败", null);
			}
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "获取用户信息异常");
		}
		return null;
	}
	/**
	 * 获取用户单个计划阶段信息
	 * @param req
	 * @param resp
	 * @param bookId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getPlans")
	public JSON getPlans(HttpServletRequest req, HttpServletResponse resp,Integer bookId){
		try {
			UserVo user = (UserVo) req.getSession().getAttribute("user");
			if (user==null){
				return Message(ERROR, "session获取用户信息失败", null);
			}
			if (bookId==null){
				return Message(ERROR, "未提交书籍id", null);
			}else {
				BookConfigVo book = bookService.getBookConfigById(bookId);
				if (book==null){
					return Message(ERROR, "未查找到当前书籍", null);
				}else {
				 List<PlanConfigVo> lp = planConfigService.getPlanConfigListByPlan(book.getBeginPlanId(), book.getEndPlanId()); //按单个计划获取对应计划配置
				 if (lp.size()>0){
					 JSONArray data = new JSONArray();
					 for (PlanConfigVo pc: lp){
						 JSONObject obj = new JSONObject();
						 obj.put("planId", pc.getPlanId());
						 obj.put("planReadCount", pc.getCount());
						 obj.put("planType",pc.getPlanType());
						 obj.put("planTitle", pc.getPlanTitle());
						 PlanProgressVo pp =  planService.getUserPlanByUidAndPlanId(user.getId(),pc.getPlanId()); //获取对应阶段用户信息
						 if (pp==null){
							 obj.put("currentReadCount", 0);
							 obj.put("currentReadRound", 0);
							 obj.put("currentSentence", null);
							 obj.put("Numberofdefeats", 0+"%");
						 } else {
							 double complete =(double) planService.getCompleteCount(pp.getCurrentReadRound(),pp.getCurrentReadCount());//计算当前阶段击败人数
							 double reading =(double) planService.getCount(pp.getCurrentReadRound()-1);
							 double percent =1.00-(complete/(complete+reading));
							 NumberFormat nt = NumberFormat.getPercentInstance();
							 nt.setMinimumFractionDigits(0);
							 obj.put("Numberofdefeats", nt.format(percent));
							 obj.put("currentReadCount", pp.getCurrentReadCount());
							 obj.put("currentReadRound", pp.getCurrentReadRound());
							 obj.put("currentSentence", pp.getCurrentSentence());
						 }
						 data.add(obj);
					 }
					 return Message(SUCCESS, "获取阶段列表成功", data);
				 }else {
					 return Message(ERROR, "为查找到当前计划", null);
				 }
				}
			}
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "获取用户信息异常");
		}
		return null;
	}
	/**
	 * 录音文件上传信息记录接口
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("/tapesCommit")
	@ResponseBody
	public JSON tapesCommit(HttpServletRequest req, HttpServletResponse resp,String tapes
			,Integer size,String flag,String comment,Integer uid, String chapter){
		try {
			if (isEmpty(tapes)){
				return Message(ERROR, "上传key不能为空", null);
			}
			if (isEmpty(flag)){
				return Message(ERROR, "未指定所属章节或计划", null);
			}
			if (size==null){
				return Message(ERROR, "文件大小未提交", null);
			}
			if (uid==null){
				return Message(ERROR, "为获取到用户id", null);
			}
			if (isEmpty(chapter)){
				return Message(ERROR, "录音章节名为空", null);
			}
			int c=0;
			c = tapesService.getTapesCounts(uid);
			if (c==500){ //上传音频数量限制查询
				return Message(ERROR, "上传音频数量已超过限制", null);
			}
			TapesRecordsVo tr = tapesService.getTapesByChapterAndUid(chapter,uid);
			if (tr!=null){
				tr.setDeleteTime(OtherUtils.getCurrentDate());
				tr.setSysflag(1);
				tapesService.saveTapesRecords(tr);
			}
//			----kanghongbo重新构造------	
			tr = new TapesRecordsVo();
			tr.setTapes(tapes);
			tr.setUid(uid);
			tr.setCommitTime(OtherUtils.getCurrentDate());
			tr.setSize(size);
			tr.setFlag(flag);
			tr.setUserComment(comment);
			tr.setChapterId(chapter);
			tapesService.saveTapesRecords(tr);
//			-------------------------		
			return Message(SUCCESS, "上传成功", tapes);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "上传异常");
		}
		
	}
}
